package com.walter.common.interceptors;

import com.walter.common.utils.TraceIdUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

import static com.walter.common.constants.CommonConstant.HEADER_TRACE_ID;


/**
 * @author Walter
 * @date 2025/1/22 下午12:49
 **/
@Slf4j
public class TraceIdFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try{
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            // 设置从请求头中获取的traceId
            TraceIdUtil.setTraceId(request.getHeader(HEADER_TRACE_ID));
            log.info("------------TraceIdFilter doFilter-------------");
            // 执行目标方法
            filterChain.doFilter(servletRequest, servletResponse);
        }finally {
            // 清除traceId
            TraceIdUtil.remove();
        }
    }
}
